<template>
  <div>
    <el-steps :active="active" finish-status="success">
      <el-step title="步骤一" />
      <el-step title="步骤二" />
      <el-step title="步骤三" />
    </el-steps>
    <main>
      <!-- 菜单 -->
      <el-form :rules="rules" ref="addItemList" label-position="top" label-width="100px" :model="goodsForm" style="max-width: 460px">
        <!-- 第一步骤 -->
        <div class="step1" v-if="active === 0">
          <el-form-item label="商品名称" prop="itemName">
            <el-input v-model="goodsForm.itemName" />
          </el-form-item>
          <el-form-item label="商品价格" prop="price">
            <el-input v-model="goodsForm.price" />
          </el-form-item>
          <el-form-item label="是否上架">
            <el-switch :active-value="1" style="--el-switch-on-color: #13ce66; " :inactive-value="0"
              v-model="goodsForm.onsale" />
          </el-form-item>
        </div>
        <!-- /第二步骤 -->
        <div class="step1" v-if="(active === 1)">
          <el-form-item label="商品描述" prop="desc">
            <el-input type="textarea" v-model="goodsForm.desc" />
          </el-form-item>
          <el-form-item label="商品分类" prop="menu">
            <el-select v-model="goodsForm.menu" :label="goodsForm.menu">
              <!-- <el-option :label="goodsForm.menu" :value="1" /> -->
              <el-option v-for="item in items" :key="item.id" :label="item.cateName" :value="item.pid" />
            </el-select>
          </el-form-item>
        </div>
        <!-- 第三步骤 -->
        <div class="step1 step3" v-if="active === 2">
          <el-upload class="upload-demo" drag 
            action="/api/updateImage" 
            :on-success="uploadSuccess"
            :before-upload="beforeUpload" 
            multiple
            >
            <img :src="goodsForm.url" style="width:200px" alt="">
            <el-icon class="el-icon--upload"><upload-filled /></el-icon>
            <div class="el-upload__text">
              将文件拖拽此处,或 <em>点击跳转</em>
            </div>
            <template #tip>
              <div class="el-upload__tip">
                只能上传jpg/或者png文件,且不超过500kb
              </div>
            </template>
          </el-upload>
        </div>
      </el-form>

    </main>

    <el-button style="margin-top: 12px" class="btn-1" @click="next" v-if="active !== 2">下一步</el-button>
    <el-button style="margin-top: 12px" class="btn-2" @click="fromSbumit" v-else>提交</el-button>
    <span v-show="spShow" class="sp1">你只是保存到草稿箱，还没提交 记得提交哦</span>
    <el-button style="margin-top: 12px;" type="warning" class="btn-4" v-if="active === 2" @click="Save(goodsForm)">修改信息保存到草稿箱</el-button>
    <el-icon class="icon-jt" v-show="spShow"><TopRight /></el-icon> 
    <el-button style="margin-top: 12px;" class="btn-3" @click="back">返回</el-button>
    
  </div>
</template>

<script setup lang="ts" name="ItemUpdate">
import { ref, reactive, onMounted } from 'vue'
import { addCate, fetchCateLists , updateCate} from '@a/cateLists'
import { updateLists ,preservation } from '@a/itemLists'
import { ElMessage } from 'element-plus'
import { useRoute, useRouter } from 'vue-router';
// 引入pinia
import useGoodsItemUp from '@/stores/ItemUp'
import useSave from '@/stores/preservation'
const route = useRoute()
const router = useRouter()

// 仓库实例
const itemStores = useGoodsItemUp()
const draftsStores = useSave()

// 路由跳转传参 基础值  


// 没有提交的提示信息
const spShow = ref(false)
// 保存到草稿箱点击事件
const Save = (goodsForm: Object) => {

      // 立即缓存 
      // 这个判断是判断localStorage里面有没有drafts这个key
      // 如果没有那就以数组嵌套对象的方式保存本次的数据
      // 如果有 那就push到localStorage里面(数组用push添加数据不会把之前的数据覆盖)
      if(!localStorage.getItem('drafts')) {
        localStorage.setItem("drafts",JSON.stringify([goodsForm]) )
        preservation(goodsForm).then((res :any) => {
            if(res.data.code === 200){
                ElMessage({
                  message: res.data.msg,
                  type: 'success',
                  duration: 1000,
                onClose: () => {
                  spShow.value = true
                }
                })
            }
          })
      }else {
        const newStores = <any>Array.from(draftsStores.drafts)
        const index = newStores.indexOf(goodsForm)
          console.log(index);
        
        if(index !== -1){
          // 不等于-1就是说明里面有这个数据
          // 有这个数据的话 就不让他保存 给他提示错误信息
            ElMessage({
            message: '草稿箱已有相同该数据,请不要重复保存',
            type: 'error',
            duration: 1000
          })
          return
        }else{
          
          newStores.push(goodsForm)
          // newStores是pinia里面已有的数据 goodsForm是本次要存进去的数据
          // return一下 然后提示草稿箱已有该数据
          console.log('===========>',newStores,'========》》',goodsForm);
          localStorage.setItem('drafts',JSON.stringify(newStores))
          preservation(goodsForm).then((res :any) => {
            if(res.data.code === 200){
                ElMessage({
                  message: res.data.msg,
                  type: 'success',
                  duration: 1000,
                onClose: () => {
                  spShow.value = true
                }
                })
            }
          })
        }
        
      }

      // 把商品数据保存到pinia
      const newStore = Array.from(draftsStores.drafts)
      newStore.push(goodsForm)
      draftsStores.SETDRAFTS(newStore)
}
// 获取商品数据 给下下拉菜单用
const items = ref<any[]>([])
const fetchItems = () => {
  fetchCateLists().then(res => {
    // console.log(res);
    if (res.data.code === 200) {
      items.value = res.data.data.lists
      console.log(items.value[0].cateName);
      // !!!!
      goodsForm.menu = items.value[0].cateName
    }
  })
}
const goodsForm = ref<any>(JSON.parse<any>(route.query.data))
// reactive({
//   goodName: '',
//   price: '',
//   onsale: 1,
//   desc: '',
//   menu: -1,
//   url: ''
// })
  // goodsForm.value = itemStores.commodityFrom

// 步骤计数
const active = ref(0)
const addItemList = ref()
// 步骤
const next = () => {
  addItemList.value.validate((valid: any) => {
    if (valid) {
      // 验证通过
      if (active.value++ > 2) active.value = 0
    } else {
      // 验证不通过
      ElMessage({
        message: '表单验证不通过',
        type: 'error'
      })
    }
  })
}
// 下拉菜单的自定义验证规则
const validator = (rule, value, callback) => {
  // console.log(callback);
  // console.log(rule);
  // console.log(value);
  if (value !== -1) {
    // -1是默认的选择 不让他选默认
    return callback()
  } else {
    // 不选择就提示
    return callback()
    // return callback(new Error('请选择一个分类 不能为默认'))
  }
}
// 定义验证规则
const rules = reactive({
  // 商品名称
  itemName: [
    {
      // true是必填验证
      required: true,
      message: '该字段必填'
    }
  ],
  // 商品是否上架
  desc: [
    {
      required: true,
      message: '该字段必填'
    }
  ],
  // 商品价钱
  price:[
    {
      required: true,
      message: '该字段必填'
    },
    // {
    //   pattern: /^[0-6]*$/,
    //   message: '请用数字填写商品价格'
    // }
  ],
  // 下拉菜单
  menu: [
    {
      required: true,
      message: '该字段必填'
    },
    {
      validator
    }
  ]
})
// 返回
const back = () => {
  if (active.value === 0) {
    router.push('/itemLists')
  }
  if (active.value-- < 1) active.value = 0
}
// 提交
const fromSbumit = () => {
  addItemList.value.validate().then(() => {
    // console.log('进来了');
    // 用的是状态开关的接口
    updateLists(goodsForm).then((res) => {
      if (res.data.code === 200) {
        // 成功后 弹出消息提示框提示用户
        ElMessage({
          message: res.data.msg,
          type: "success",
          duration: 1500,
          onClose: () => {
            // 刷新页面
            router.push('./itemLists')
          },
        });
      } else {
        ElMessage({
          message: '表单验证没有通过',
          type: "error",
        });
      }
    });
  });
};
// 上传文件 大小 
const beforeUpload = (file: any) => {
  // 限制上传文件的体积  byte
  if (file.size > 1024 * 1024) {
    alert("体积超出1M");
    return false;
  } else {
    return true;
  }
};
// 成功的钩子
const uploadSuccess = (res: any) => {

    ElMessage({
      type: "success",
      message: "上传成功",
    });
};
// 失败的钩子
const uploadError = (res: any) => {

    ElMessage({
      message: "上传失败，请重新上传",
    });
}

onMounted(() => {
  
  fetchItems()
  useGoodsItemUp()
})
</script>

<style lang="scss" scoped>
main {
  position: relative;
  left: -250px;
  margin: 20px 50%;
  width: 500px;
  height: 300px;
  // background: palegreen;
}

.btn-1,
.btn-2 {
  display: block;
  position: absolute;
  left: 10px;
  margin: 20px 50%;
}

.btn-3 {
  display: block;
  position: absolute;
  left: 90px;
  margin: 20px 50%;
}
.btn-4 {
  display: block;
  position: absolute;
  left: 180px;
  margin: 20px 50%;
}
.sp1{
  color: #C4968B;
  font-size: 10px;
  width: 300px;
  display: block;
  position: absolute;
  left: -40px;
  top: 425px;
  margin: 20px 50%;
}
.icon-jt{
  font-size: 30px;
  color: #EB9867;
  width: 110px;
  display: block;
  position: absolute;
  left: -15px;
  top: 510px;
  margin: 20px 50%;
}
</style>